package chuangyi.com.org.DOMIHome;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.solidfire.gson.internal.LinkedTreeMap;
import com.umeng.socialize.UMShareAPI;

import java.util.Locale;
import java.util.Stack;

import chuangyi.com.org.DOMIHome.Fragments.CommonFragment;
import chuangyi.com.org.DOMIHome.Fragments.HomeFragment;
import chuangyi.com.org.DOMIHome.Fragments.VideoFragment;
import chuangyi.com.org.DOMIHome.Utils.HttpUtil;
import chuangyi.com.org.DOMIHome.Utils.Utils;
import chuangyi.com.org.DOMIHome.Utils.WebApi;
import chuangyi.com.org.DOMIHome.adapter.BindingListItem;
import chuangyi.com.org.ViewModel.ApplyExpertContractModel;
import chuangyi.com.org.ViewModel.ApplyExpertProgress;
import chuangyi.com.org.ViewModel.CommunicationModel;
import chuangyi.com.org.ViewModel.PayItem;
import chuangyi.com.org.ViewModel.PayModel;
import chuangyi.com.org.ViewModel.PersonalHome;
import chuangyi.com.org.ViewModel.User;
import chuangyi.com.org.ViewModel.UserInfoModel;
import chuangyi.com.org.ViewModel.VideoDetail;
import chuangyi.com.org.ViewModel.VideoPayModel;
import chuangyi.com.org.ViewModel.WebViewModel;
//import fm.jiecao.jcvideoplayer_lib.JCVideoPlayer;
//import io.vov.vitamio.widget.MediaController;

public class HomeActivity extends AppCompatActivity {
    public static final int REQUEST_LOGIN = 1;
    public static final int REQUEST_SHARE = 2;
    public static final int REQUEST_IMAGE = 3;
    public static final int REQUEST_SORT = 4;
    public static final int REQUEST_WAIT = 5;
    public static final int REQUEST_BLOCKRESULT = 6;
    public static final int REQUEST_PAY = 7;
    public static final int REQUEST_DIALOGTIP = 8;
    public static final int REQUEST_JOB = 9;
    public static final int REQUEST_INDUSTRY = 10;
    public static final int REQUEST_CONFIRM_APPLY_EXPERT = 11;

    private long lastPressed;
    public ImageLoader imageLoader = ImageLoader.getInstance();
    // 管理已启动的Fragment
    private static Stack<Fragment> fragmentStack;
    private static HomeActivity current;
    private static long lastClickTime;

    static {
        fragmentStack = new Stack<Fragment>();
    }

    public static HomeActivity getCurrent() {
        return current;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);

        }
        current = this;
        imageLoader.init(ImageLoaderConfiguration.createDefault(this));
        setContentView(R.layout.a_main);
//        View content = findViewById(R.id.content);
        fragmentStack.clear();
        FragmentManager fm = getFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();
        HomeFragment fragment = new HomeFragment();
        transaction.add(R.id.content, fragment);
        transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
        transaction.addToBackStack(null);
        transaction.commit();
        fragmentStack.push(fragment);

        if (LoginActivity.current != null && LoginActivity.current.isDestroyed() == false) {
            LoginActivity.current.finish();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onBackPressed() {
        if (exitFullScreen()) {
            return;
        }
        if (fragmentStack.size() > 1) {
            popFragmentInner();
        } else {
            exit();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
        CommonFragment fragment = (CommonFragment) fragmentStack.peek();
        if (fragment != null && fragment.getDataModel() != null && fragment.getDataModel() instanceof WaitActivityResult) {
            WaitActivityResult waitActivityResult = (WaitActivityResult) fragment.getDataModel();
            if (waitActivityResult != null) {
                waitActivityResult.onActivityResult(requestCode, resultCode, data);
            }
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);

        if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            WindowManager.LayoutParams attrs = getWindow().getAttributes();
            attrs.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
            getWindow().setAttributes(attrs);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
        } else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
            WindowManager.LayoutParams attrs = getWindow().getAttributes();
            attrs.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
            getWindow().setAttributes(attrs);
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
        }

    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            if (isFastDoubleClick()) {
                return true;
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    private void exit() {
        if ((System.currentTimeMillis() - lastPressed) > 2000) {
            Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
            lastPressed = System.currentTimeMillis();
        } else {
            super.finish();
        }
    }

    private boolean exitFullScreen() {
        if (fragmentStack.peek() instanceof VideoFragment) {
            VideoFragment fragment = (VideoFragment) fragmentStack.peek();
            return fragment.backPressed();
        }
        return false;
    }

    private void doPopFragment(FragmentManager fragmentManager) {
        closeSoftKeyboard(this);
        fragmentStack.pop();
        fragmentManager.popBackStack();
        showOrHideVideoView(true);
        if (fragmentStack.peek() instanceof CommonFragment) {
            CommonFragment fragment = (CommonFragment) fragmentStack.peek();
            if (fragment.getDataModel() != null && fragment.getDataModel() instanceof RefreshContent) {
                RefreshContent refreshContent = (RefreshContent) fragment.getDataModel();
                refreshContent.refresh();
            }
        }
    }

    private void popFragmentInner() {
        FragmentManager fragmentManager = getFragmentManager();
        if (fragmentStack.size() <= 1) {
            return;
        }
        if (fragmentStack.peek() instanceof CommonFragment) {
            CommonFragment fragment = (CommonFragment) fragmentStack.peek();
            if (fragment.getDataModel() instanceof SaveContent) {
                SaveContent saveContent = (SaveContent) fragment.getDataModel();
                if (saveContent != null) {
                    if (saveContent.check()) {
                        saveContent.save();
                    }
                    return;
                }
            }
        }
        doPopFragment(fragmentManager);
    }

    private void goback() {
        FragmentManager fragmentManager = getFragmentManager();
        if (fragmentStack.size() > 1) {
            doPopFragment(fragmentManager);
        }
    }

    private static void closeSoftKeyboard(Activity activity) {
        InputMethodManager mInputKeyBoard = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (activity.getCurrentFocus() != null) {
            mInputKeyBoard.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        }
    }

    public static CommonFragment openVideoDetail(final Context context, final int videoId, VideoDetail detail) {
        VideoFragment fragment = new VideoFragment();
        fragment.setLayoutId(R.layout.f_course_detail);
        fragment.setVariableId(BR.detail);
        fragment.setDataModel(detail);
        fragment.setPlayCallback(new VideoFragment.StartPlayCallback() {
            @Override
            public boolean allowPlay() {
                LinkedTreeMap map = WebApi.getMemberPrice(context, videoId);
                if (map == null)
                    return true;
                LinkedTreeMap price = (LinkedTreeMap) map.get("dj");

                final VideoPayModel model = new VideoPayModel(context);

                model.setVideoPrice(Utils.getDoubleValue(price.get("price")));
                model.setScore(Utils.getDoubleValue(price.get("jifen")));

                price = (LinkedTreeMap) map.get("jd");
                model.setSeasonPrice(Utils.getDoubleValue(price.get("price")));
                price = (LinkedTreeMap) map.get("qb");
                model.setAllVideoPrice(Utils.getDoubleValue(price.get("price")));

                if (WebApi.getVideoPlay(context, videoId)) {
                    return true;
                } else {
                    // 显示视频支付
                    model.setPayCallback(new PayModel.Callback() {
                        @Override
                        public boolean onPay(final PayItem item) {
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    String buyType = "dj";
                                    if (model.isSeasonSelected()) {
                                        buyType = "jd";
                                    } else if (model.isAllSelected()) {
                                        buyType = "qb";
                                    }
                                    if (item.getType() != PayModel.PAY_SCORE) {
                                        String type = item.getType() == PayModel.PAY_ALI ? "ali" : "wx";
                                        String result = WebApi.buyCourse(context, videoId, type, buyType);
                                        if (result == null)
                                            return;
                                        if (item.getType() == PayModel.PAY_ALI) {
                                            LinkedTreeMap map = HttpUtil.fromJson(result, LinkedTreeMap.class);
                                            result = (String) map.get("orderinfo");
                                            item.setPayData(result);
                                        } else if (item.getType() == PayModel.PAY_WX) {
                                            LinkedTreeMap map = HttpUtil.fromJson(result, LinkedTreeMap.class);
                                            map = (LinkedTreeMap) map.get("orderinfo");
                                            WxPayInfoModel model = new WxPayInfoModel();
                                            model.setAppid((String) map.get("appid"));
                                            model.setPartnerid((String) map.get("partnerid"));
                                            model.setPrepayid((String) map.get("prepayid"));
                                            model.setTimestamp((String) map.get("timestamp"));
                                            model.setNoncestr((String) map.get("noncestr"));
                                            model.setPackage((String) map.get("package"));
                                            model.setSign((String) map.get("sign"));

                                            item.setPayData(model);
                                        }
                                    } else {
                                        if (buyType != "dj") {
                                            model.showToast("不支持积分支付");
                                            return;
                                        }
                                        scorePayConfirm(videoId, model);
                                    }
                                    item.getParent().callPay(item);
                                }
                            }).start();
                            return false;
                        }
                    });
                    // 启动支付对话框
                    model.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            PopupActivity.startActivity((Activity) context,
                                    R.layout.v_dialog_pay, BR.payModel, model);
                        }
                    });
                    //dj jd qb
                    return false;
                }
            }
        });
        HomeActivity.switchFragment((Activity) context, fragment);
        return fragment;
    }

    private static void scorePayConfirm(final int videoId, final VideoPayModel model) {
        ((Activity) model.getContext()).runOnUiThread(new Runnable() {
            @Override
            public void run() {
                new AlertDialog.Builder(model.getContext()).setTitle("提示").setMessage(
                        String.format(Locale.CHINESE, "确定使用%.2f积分支付此视频吗？", model.getScore()))
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        LinkedTreeMap map = WebApi.payVideoByScore(model.getContext(), videoId);
                                        if (map != null) {
                                            model.notifyPayResult(true);
                                        } else {
                                            model.notifyPayResult(false);
                                        }
                                    }
                                }).start();
                            }
                        })
                        .setNegativeButton("取消", null).show();
            }
        });

    }

    public static void popFragment() {
        HomeActivity.current.popFragmentInner();
    }

    public static void cancelFragment() {
        HomeActivity.current.goback();
    }

    public static boolean isFastDoubleClick() {
        long time = System.currentTimeMillis();
        long timeD = time - lastClickTime;
        lastClickTime = time;
        return timeD <= 200;
    }

    /**
     * 切换显示的Fragment
     *
     * @param activity
     * @param fragment
     */
    public static void replaceFragment(Activity activity, Fragment fragment) {
        FragmentManager fragmentManager = activity.getFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
        transaction.replace(R.id.content, fragment);
        fragmentStack.push(fragment);
        closeSoftKeyboard(activity);
//        transaction.replace(R.id.content, fragment);
        transaction.addToBackStack(null);
        transaction.commit();
    }

    /**
     * 切换显示的Fragment
     *
     * @param activity
     * @param fragment
     */
    public static void switchFragment(Activity activity, Fragment fragment) {
        showOrHideVideoView(false);
        closeSoftKeyboard(activity);
        FragmentManager fragmentManager = activity.getFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
        transaction.add(R.id.content, fragment);
        fragmentStack.push(fragment);
//        transaction.replace(R.id.content, fragment);
        transaction.addToBackStack(null);
        transaction.commit();
    }

    private static void showOrHideVideoView(boolean show) {
        if (fragmentStack.peek() instanceof VideoFragment) {
            VideoFragment fragment = (VideoFragment) fragmentStack.peek();
            if (show) {
                fragment.showVideoView();
            } else {
                fragment.hideVideoView();
            }
        }
    }

    /**
     * 显示个人中心页
     *
     * @param uid
     */
    public static void showPersonalCentral(Context context, int uid) {
        CommonFragment fragment = new CommonFragment();
        PersonalHome personalHome = new PersonalHome(context, uid);
//        bundle.putInt("layoutId", R.layout.f_personal_home);
//        fragment.setArguments(bundle);
        fragment.setLayoutId(R.layout.f_personal_home);
        fragment.setDataModel(personalHome);
        fragment.setVariableId(BR.personal);
        HomeActivity.switchFragment((Activity) context, fragment);
    }

    /**
     * 显示个人中心页
     *
     * @param uid
     */
    public static void showPersonalCentral(Context context, int uid, boolean isExpert) {
        CommonFragment fragment = new CommonFragment();
        Bundle bundle = new Bundle();
        PersonalHome personalHome = new PersonalHome(context, uid);
        personalHome.setExpert(isExpert);
//        bundle.putInt("layoutId", R.layout.f_personal_home);
        fragment.setLayoutId(R.layout.f_personal_home);
//        fragment.setArguments(bundle);
        fragment.setDataModel(personalHome);
        fragment.setVariableId(BR.personal);
        HomeActivity.switchFragment((Activity) context, fragment);
    }

    public static void notifyListChange(int action, BindingListItem item) {
        if (fragmentStack.peek() instanceof CommonFragment) {
            CommonFragment fragment = (CommonFragment) fragmentStack.peek();
            if (fragment.getDataModel() instanceof NotifyListChanged) {
                NotifyListChanged notify = (NotifyListChanged) fragment.getDataModel();
                if (notify != null) {
                    notify.notifyListChanged(action, item);
                }
            }
        }
    }

    public static void startWebViewFragment(Context context, String url) {
        WebViewModel model = new WebViewModel(context);
        model.setUrl(url);
        CommonFragment fragment = new CommonFragment();
        fragment.setDataModel(model);
        fragment.setLayoutId(R.layout.f_webview);
        fragment.setVariableId(BR.webModel);
        HomeActivity.switchFragment((Activity) context, fragment);
    }

    public static void beginApplyExpert(Context context) {
        final Activity activity = (Activity) context;
        new Thread(new Runnable() {
            @Override
            public void run() {
                final int result = WebApi.isDone(activity);

                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        CommonFragment fragment = new CommonFragment();
                        switch (result) {
                            case CommunicationModel.GOTO_COMPLETE_INFO:
                                final UserInfoModel model = new UserInfoModel(activity);
                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        model.getMoreInfo();
                                    }
                                }).start();
                                model.setAppling(true);
                                fragment.setDataModel(model);
                                fragment.setLayoutId(R.layout.f_apply_expert_complete_info);
                                fragment.setVariableId(BR.userInfo);
                                break;
                            case CommunicationModel.GOTO_PROGRESS_PAGE:
                                ApplyExpertContractModel contractModel = new ApplyExpertContractModel(activity);
                                fragment.setLayoutId(R.layout.f_apply_expert_contract);
                                fragment.setVariableId(BR.contract);
                                fragment.setDataModel(contractModel);
                                break;
                            default:
                                return;
                        }
                        HomeActivity.switchFragment(activity, fragment);
                    }
                });
            }
        }).start();
    }

    public static void showApplyProgress(Context context) {
        ApplyExpertProgress progress = new ApplyExpertProgress(context);
        CommonFragment fragment = new CommonFragment();
        fragment.setVariableId(BR.applyProgress);
        fragment.setLayoutId(R.layout.a_apply_expert);
        fragment.setDataModel(progress);
        HomeActivity.popFragment();
        HomeActivity.switchFragment((Activity) context, fragment);
    }

    /**
     * 退出登录
     */
    public static void exit(Context context) {
        Activity activity = (Activity) context;
        if (activity != null && !activity.isDestroyed() && !activity.isFinishing()) {
            LoadingDialog.getInstance(activity).dismiss();
            Intent intent = new Intent();
            intent.setClass(context, LoginActivity.class);
            Bundle bundle = new Bundle();
            bundle.putString("phone", User.getCurrentUser().getPhone());
            DBManager.getInstance(activity).deleteAllUser();
            activity.startActivity(intent);
            activity.finishAffinity();
        }
    }
}
